package com.repeat.member.mq.consump;


import com.api.openfeign.client.UserClient;
import com.api.openfeign.dto.UserDto;
import com.repeat.member.model.RewardRecords;
import com.repeat.member.model.User;
import com.repeat.member.repository.RewardRecordRepository;
import com.repeat.member.repository.UserRepository;
import com.shop.common.constant.RabbitFinalConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.Map;

@Component
@Slf4j
public class UserPointsConsump {

    @Autowired
    private UserClient userClient;

    @Autowired
    private RewardRecordRepository recordRepository;
    @Autowired
    private UserRepository userRepository;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitFinalConstant.REGISTER_QUEUE),
            exchange = @Exchange(name = RabbitFinalConstant.POINTS_EXCHANGE),
            key = {RabbitFinalConstant.REGISTER_ROUTING_KEY}
    ))
    public void register_points(String msg) {
        log.info("收到一个注册消息: {}",msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitFinalConstant.SING_QUEUE),
            exchange = @Exchange(name = RabbitFinalConstant.POINTS_EXCHANGE),
            key = {RabbitFinalConstant.SING_ROUTING_KEY}
    ))
    @Transactional
    public void sign_points(Map<String,Object> msg) {
        //1.判断用户是否是一个有效用户
        Long userId = ((Number) msg.get("userId")).longValue();
        Integer points = (Integer) msg.get("points");
        Long RecordId = ((Number) msg.get("RecordId")).longValue();
        Integer RewardType = (Integer) msg.get("RewardType");
        UserDto userDto = userClient.userId(userId);
        if(userDto != null && userDto.getEnabled()) {
              //2.添加消息记录
            RewardRecords rewardRecords =  new RewardRecords();
            rewardRecords.setUserId(userId);
            rewardRecords.setRewardPoints(points);
            rewardRecords.setSignRecordId(RecordId);
            rewardRecords.setRewardType(RewardType);
            rewardRecords.setCreatedAt(LocalDateTime.now());
            recordRepository.save(rewardRecords);
            //3.用户添加
            User user = userRepository.findById(userId).orElse(null);
            if (user != null) {
                user.setPoints(user.getPoints() + points);
                userRepository.save(user);
            }
        }else {
            log.info("用户不存在或者不是有效{}",msg);
        }
        log.info("收到一个签到消息用户id: {} 赠送积分{} 用户:{}",userId,points,userDto);
    }

}
